package creational.pattern.factory.help;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Autor: yuanyongan
 * @Description: 这里主要是实现了ApplicationContextAware接口，
 * 在Spring项目中，实现了这个接口，会自动在项目启动通过@Component或者其他注解将当前对象注入之后
 * 会调用setApplicationContext方法初始化applicationContext
 * @Date 2023/1/9 9:22
 */

@Component
public class SpringApplicationUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringApplicationUtils.applicationContext == null){
            SpringApplicationUtils.applicationContext = applicationContext;
        }
    }

    public static <T> T getBean(Class<T> beanType){
        return applicationContext.getBean(beanType);
    }

    public static Object getBean(String beanName){
        return  applicationContext.getBean(beanName);
    }
}
